<?php

namespace Home\Controller;

class AdverController extends HomeController
{
    //发布广告首页
    public function index()
    {
        $btcData = btcdata("https://www.bbitworld.com/api/ticker/getTicker?market=btc_cny");
        $countryData = M('Country')->field('zh_name,code,code2')->where('is_show = 1')->select();
        $moneytype = M('MoneyType')->where('status = 1')->select();
        foreach ($countryData as $k => $v) {
            $countryData[$k]['name'] = $v['code'] . $v['zh_name'];
            unset($countryData[$k]['zh_name']);
            unset($countryData[$k]['code']);
        }

        $asd = explode(':', $btcData);

        $btcprice = substr($asd[18], 0, 14);

        $arr = array();

        $arr['countryData'] = $countryData;

        $arr['moneytype'] = $moneytype;

        $arr['btc'] = $btcprice;

        $this->ajaxReturn($arr, 'JSON');
    }

    //发布广告
    public function addAdver($trade_type, $country, $money_type, $coin, $full_num, $price, $num, $min_price, $max_limit, $min_limit, $pay_type, $message, $userid, $token)
    {
        $user = M('User')->where('id = ' . $userid)->find();

        $this->checkLog($userid, $token);

        if ($user['sm_is_ok'] != 2) {
            $this->ajaxError('请先完成实名认证');
        }

        if ($min_price > $price) {
            $this->ajaxError('最低价格不能高于市场价格');
        }

        $userData = M('UserCoin')->where(array(
            'userid' => $userid
        ))->find();

        if ($num == '') {
            $this->ajaxError('请输入数量');
        }

        if ($num == 0) {
            $this->ajaxError('您输入的数量不能为0');
        }

        if (!check($price, 'double')) {
            $this->ajaxError('交易价格格式错误');
        }

        if (!check($num, 'double')) {
            $this->ajaxError('交易数量格式错误');
        }

        if ($country == '') {
            $this->ajaxError('请输入所在地');
        }

        if ($trade_type == '') {
            $this->ajaxError('请输入广告类型');
        }

        if ($money_type == '') {
            $this->ajaxError('请输入交易的币种类型');
        }

        if ($full_num == '') {
            $this->ajaxError('请输入溢出比例');
        }

        if ($min_price == '') {
            $this->ajaxError('请输入最低价格');
        }

        if ($min_price == 0){
            $this->ajaxError('最小金额不能为0');
        }
        if ($min_limit == '') {
            $this->ajaxError('请输入交易金额最低限制');
        }

        if ($min_limit == 0) {
            $this->ajaxError('最小限额不能为0');
        }

        if ($max_limit == 0) {
            $this->ajaxError('最大限额不能为0');
        }

        if ($max_limit == '') {
            $this->ajaxError('请输入交易金额最高限制');
        }

        if ($max_limit < $min_limit) {
            $this->ajaxError('您的价格区间有问题');
        }

        if ($pay_type == '') {
            $this->ajaxError('请输入支付类型');
        }

        if ($message == ''){
            $this->ajaxError('请输入交易说明');
        }

        if ($trade_type == 1) {
            if ($userData[$coin] < $num) {
                $this->ajaxError('您的虚拟币可用余额不足');
            }
        }
        $m = M();
        //$m->execute('autocommit = 0');
        $m->execute('lock table trade_adver write , trade_user_coin write');

        $rs[] = M('Adver')->add(array(
            'userid' => $user['id'],
            'trade_type' => $trade_type,
            'country' => $country,
            'money_type' => $money_type,
            'price' => $price,
            'coin_type' => $coin,
            'min_price' => $min_price,
            'min_limit' => $min_limit,
            'max_limit' => $max_limit,
            'pay_type' => $pay_type,
            'message' => $message,
            'full_num' => $full_num,
            'status' => 1,
            'addtime' => time(),
            'num' =>  $num,
            'numt' => $num
        ));

        if ($trade_type == 1) {
            //加锁表
            $rs[] = $m->table('trade_user_coin')->where(array(
                'userid' => $userid
            ))->setDec($coin, $num);
            $rs[] = $m->table('trade_user_coin')->where(array(
                'userid' => $userid
            ))->setInc($coin . 'd', $num);
        }

        //做数组验证
        if (check_arr($rs)) {
            $m->execute('commit');
            $m->execute('unlock tables');
            $this->ajaxSuccess('发布成功');
        } else {
            $m->execute('rollback');
            $m->execute('unlock tables');
            $this->ajaxError('发布失败');
        }
    }

    //我出售的广告
    public function mySellAdver($userid, $token)
    {
        $this->checkLog($userid, $token);

        $myAdver = M('Adver')->field('id,trade_type,status,addtime,price,full_num,country')->where(array(
            'type' => 1,
            'userid' => $userid,
            'status' => 1
        ))->select();

        $this->ajaxReturn($myAdver, 'JSON');
    }

    //我购买的广告
    public function myBuyAdver($userid, $token)
    {
        $this->checkLog($userid, $token);

        $myAdver = M('Adver')->field('id,trade_type,status,addtime,price,full_num,country')->where(array(
            'type' => 2,
            'userid' => $userid,
            'status' => 1
        ))->select();
        $this->ajaxReturn($myAdver, 'JSON');
    }

    //我下架的购买广告
    public function myDelBuyAdver($userid, $token)
    {
        $this->checkLog($userid, $token);

        $myAdver = M('Adver')->field('id,trade_type,status,addtime,price,full_num,country')->where(array(
            'type' => 2,
            'userid' => $userid,
            'status' => 0
        ))->select();

        $this->ajaxReturn($myAdver, 'JSON');
    }

    //我下架的出售广告
    public function myDelSellAdver($userid, $token)
    {
        $this->checkLog($userid, $token);

        $myAdver = M('Adver')->field('id,trade_type,status,addtime,price,full_num,country')->where(array(
            'type' => 1,
            'userid' => $userid,
            'status' => 0
        ))->select();
        $this->ajaxReturn($myAdver, 'JSON');
    }

    //下架商品  id是广告的id
    public function delAdver($id = 39, $userid = 37)
//    public function delAdver($id, $userid, $token)
    {
        //$this->checkLog($userid, $token);

        $adverData = M('Adver')->where(array(
            'id' => $id
        ))->find();

        if ($adverData['status'] == 0) {
            $this->ajaxError('您的广告已经下架');
        }

        //TODO 验证广告拥有权  已修改
        if ($adverData['userid'] != $userid) {
            $this->ajaxError('此广告不是您发布的');
        }


        $tradeingData = M('Trade')->where('status = 1 and adver_id = ' .$id)->select();
        $coin = $adverData['coin_type'];
        if ($adverData['trade_type']  == 1){
            if ($tradeingData){
                foreach ($tradeingData as $k => $v) {
                    $rs = M('Adver')->where(array(
                        'id' => $id
                    ))->setDec('numd' , $v['num']);

                    if (!$rs){
                        $log = '错误 卖单  返回 广告冻结出错 减numd id :' .$id .', 订单id :' .$v['id'];
                        mlog($log);
                        break;
                    }

                    $rs = M('Adver')->where(array(
                        'id' => $id
                    ))->setInc('num' , $v['num']);

                    if (!$rs) {
                        $log = '错误 卖单  返回 广告冻结出错 加num id :' .$id .', 订单id :' .$v['id'];
                        mlog($log);
                    }
                }

            }
            $rs = M()->table('trade_user_coin')->where(array(
                'userid' => $userid,
            ))->setDec($coin . 'd', $adverData['num']);

            $rs = M()->table('trade_user_coin')->where(array(
                'userid' => $userid,
            ))->setInc($coin, $adverData['num']);

            $res = M('Adver')->where(array(
                'id' => $id
            ))->setField('status' ,0);
        }


        if ($adverData['trade_type'] == 2) {
            if ($tradeingData) {
                foreach ($tradeingData as $k => $v) {
                    $rs = M('UserCoin')->where(array(
                        'userid' => $v['trade_id']
                    ))->setDec($coin . 'd' , $v['num']);

                    if (!$rs){
                        $log = '错误 买单  返回 资金冻结出错 减numd id :' .$id .', 订单id :' .$v['id'];
                        mlog($log);
                    }

                    $rs = M('UserCoin')->where(array(
                        'userid' => $v['trade_id']
                    ))->setInc($coin , $v['num']);

                    if (!$rs) {
                        $log = '错误 买单  返回 资金冻结出错 加numd id :' .$id .', 订单id :' .$v['id'];
                        mlog($log);
                    }
                }
            }
            $res = M('Adver')->where(array(
                'id' => $id
            ))->setField('status' ,0);
        }

        if ($res){
            $this->ajaxSuccess('下架成功');
        }else{

            $this->ajaxError('下架失败');
        }

        //        if ($adverData['deal'] != 0) {
//            $reback = $adverData['num'] - $adverData['deal'];
//        }else{
//            $reback = 0;
//        }
//        $usercoin = M('UserCoin')->where(array(
//            'userid' => $userid
//        ))->find();
//
//        $coin = $adverData['coin_type'];
//
//        if ($adverData['trade_type'] == 1){
//            if ($usercoin[$coin] == 0) {
//                $this->ajaxError("没有冻结金额");
//            }
//
//            $m = M();
//            //$m->execute('autocommit = 0');
//            $m->execute('lock table trade_adver write , trade_user_coin write');
//
//            $rs[] = $m->table('trade_user_coin')->where(array(
//                'userid' => $userid,
//            ))->setDec($coin .'d', $reback);
//            //dump($m->getLastSql());die;
//            $rs[] = $m->table('trade_user_coin')->where(array(
//                'userid' => $userid,
//            ))->setInc($coin , $reback);
//
//            $rs[] = $m->table('trade_adver')->where("id =" . $id)->save(array(
//                'status' => 0
//            ));
//        }
//
//        if ($adverData['trade_type'] == 2) {
//            $rs = $m->table('trade_adver')->where("id =" . $id)->save(array(
//                'status' => 0
//            ));
//        }

//        if (check_arr($rs)) {
//            $m->execute('commit');
//            $m->execute('unlock tables');
//            $this->ajaxSuccess('下架成功');
//        } else {
//            $m->execute('rollback');
//            $m->execute('unlock tables');
//            $this->ajaxError('下架失败');
//        }
    }
}